package com.base.service.impl;

import java.util.Date;
import java.util.List;

import com.base.service.PersonnelService;
import com.common.bean.Personnel;
import com.common.exception.SystemException;
import com.common.util.AbstractManager;
import com.common.util.PagerModel;

public class PersonnelServiceImpl extends AbstractManager implements
		PersonnelService {

	public String addPersonnel(Personnel personnel) {//TODO 防止主键重复count方法
		if(personnel == null) {
			throw new SystemException("personnel instance is null.");
		}
		String staffcode = "";
		String deptcode = personnel.getDepartment().getDeptcode();
		int index = findAllpersonnelCount(deptcode);
		staffcode = deptcode + "" + (index < 10 ? ("0" + index) : (index + "")); 
		personnel.setStaffcode(staffcode);
		personnel.setCreatedate(new Date());
		
		this.getHibernateTemplate().save(personnel);
		return staffcode;
	}

	@SuppressWarnings("unchecked")
	public List<Personnel> findAllPersonnels() {
		String hql = "from Personnel ";
		
		return this.getHibernateTemplate().find(hql);
	}

	public Personnel findPersonnel(String staffcode) {
		return (Personnel) this.getHibernateTemplate().get(Personnel.class, staffcode);
	}

	public void removePersonnel(String staffcode) {
		Personnel personnel = findPersonnel(staffcode);
		this.getHibernateTemplate().delete(personnel);
	}
	
	@SuppressWarnings("unchecked")
	private int findAllpersonnelCount(String deptcode) {
		String hql = "from Personnel person where person.department.deptcode = ?" ;
		int result = 1 ; //(Integer).get(0);
		
		List<Personnel> liperson = getHibernateTemplate().find(hql,deptcode);
		
		for(Personnel person:liperson){
			String str = person.getStaffcode();
			int begin = str.length() - 2;
			int temp = Integer.parseInt(str.substring(begin));
			
			if(result <= temp ) {
				result = temp + 1 ;
			}
		}
		
		return result;
	}

	public PagerModel findPersonnels(int offset , int pagesize) {
		String hql = "from Personnel order by staffcode";
		return this.searchPaginated(hql, offset, pagesize);
	}

	public void updatePersonnel(Personnel personnel) {
		if(personnel == null ) {
			throw new SystemException("personnel instance is null.");
		}
		
		if(personnel.getStaffcode() == null || personnel.getStaffcode() == "") {
			throw new SystemException("personnel staffcode is null. ");
		}
		
		this.getHibernateTemplate().update(personnel);
	}
	
}
